package com.woyowodaows.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.gyf.barlibrary.ImmersionBar;
import com.woyowodaows.R;
import com.woyowodaows.activity.mine.AccountSecurityActivity;
import com.woyowodaows.activity.mine.VersionUpdateBean;
import com.woyowodaows.activity.mine.VersionUpdateDataBean;
import com.woyowodaows.adapter.viewpager.MyFragmentPagerAdapter;
import com.woyowodaows.base.BaseActivity;
import com.woyowodaows.bean.home.UserDataBean;
import com.woyowodaows.dialog.VersionUpdateDialog;
import com.woyowodaows.fragment.home.HomePageFragment;
import com.woyowodaows.fragment.mine.MineFragment;
import com.woyowodaows.request.HttpAsyncTask;
import com.woyowodaows.request.HttpRequestListener;
import com.woyowodaows.request.InterfaceUrl;
import com.woyowodaows.utils.ActivityManagerUtils;
import com.woyowodaows.utils.DisplayUtils;
import com.woyowodaows.utils.SDCardUtils;
import com.woyowodaows.weight.NoScrollViewPager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends FragmentActivity implements RadioGroup.OnCheckedChangeListener {
    private RadioGroup rbArray;
    private RadioButton rbHomePage,rbMine;
    private FragmentManager fm;
    private ArrayList<Fragment> listFragment = new ArrayList<>();
    private NoScrollViewPager vpLayouts;
    private AlertDialog exitDialog;//退出应用提示框


    //当前显示的fragment
    private static final String CURRENT_FRAGMENT = "STATE_FRAGMENT_SHOW";
    private int currentIndex = 0;
    private ImmersionBar mImmersionBar;

    private VersionUpdateDialog versionUpdateDialog;//版本更新

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        fm = getSupportFragmentManager();
        setContentView(R.layout.activity_main);
        initView();
        initImmersionBar();
        setTransparencyStatusBar();
        versionUpdate();
        rbArray.setOnCheckedChangeListener(this);
        listFragment.add(new HomePageFragment());//首页
        listFragment.add(new MineFragment());//我的
        MyFragmentPagerAdapter pagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(), null, listFragment);
        vpLayouts.setAdapter(pagerAdapter);
        vpLayouts.setOffscreenPageLimit(3);
        vpLayouts.setNoScroll(true);
    }

    /**
     * 使用show() hide()切换页面
     * 显示fragment
     */
    private void showFragment() {
        vpLayouts.setCurrentItem(currentIndex,false);
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //“内存重启”时保存当前的fragment名字
        outState.putInt(CURRENT_FRAGMENT, currentIndex);
        super.onSaveInstanceState(outState);
    }

    private void initView() {
        rbArray = (RadioGroup) findViewById(R.id.rb_array);
        rbHomePage = (RadioButton) findViewById(R.id.rb_home_page);
        rbMine = (RadioButton) findViewById(R.id.rb_mine);
        vpLayouts = (NoScrollViewPager) findViewById(R.id.vp_layouts);

    }


    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
        switch (checkedId) {
            case R.id.rb_home_page:
                currentIndex = 0;
                showFragment();
                break;
            case R.id.rb_mine:
                currentIndex = 1;
                showFragment();
                break;
        }
    }


    protected void initImmersionBar() {
        //在BaseActivity里初始化
        mImmersionBar = ImmersionBar.with(this);
        mImmersionBar.init();
    }

    //设置沉淀状态栏
    private void setTransparencyStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            mImmersionBar.fitsSystemWindows(false).statusBarDarkFont(false).transparentStatusBar().init();
        }else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            mImmersionBar.fitsSystemWindows(true).statusBarColor(R.color.text_gray_333).keyboardEnable(true).statusBarDarkFont(true).init();
        }
    }


    /**
     * 按返回键弹出提示框 提示用户是否退出
     *
     * @param keyCode
     * @param event
     * @return
     */

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (exitDialog == null) {
                    exitDialog = new AlertDialog.Builder(MainActivity.this)
                            .setTitle("提示:")
                            .setMessage("亲！您确定要退出在线报修吗？")
                            .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    exitDialog.dismiss();
                                    finish();
                                    System.exit(0);
                                }
                            }).setPositiveButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    exitDialog.dismiss();
                                }
                            }).create();
                }
                exitDialog.show();
                break;
        }
        return true;
    }




    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mImmersionBar != null)
            mImmersionBar.destroy();  //在BaseActivity里销毁
        DisplayUtils.closeTransparencyStatusBar(this);

    }

    /**
     * 版本更新
     */
    private void versionUpdate() {
        Map<String, Object> mapParameter = new HashMap<>();
        HttpAsyncTask.getInstance().onPostParam(this, "", false, InterfaceUrl.QUERYNEWVERSION, VersionUpdateDataBean.class, mapParameter,new HttpRequestListener() {
            @Override
            public void onSuccess(Object result) {
                if (result != null) {
                    VersionUpdateDataBean bean = (VersionUpdateDataBean) result;
                    if (bean.getResult() == HttpAsyncTask.SUCCESS) {
                        VersionUpdateBean versionUpdateBean = bean.getData();
                        if (Integer.valueOf(versionUpdateBean.getCurrentVersion()) > SDCardUtils.getVersionCode(MainActivity.this)) {
                            showVersionUpdateDialog(versionUpdateBean);
                        }
                    }
                }
            }

            @Override
            public void onError(String message) {
            }
        });
    }



    /**
     * 下载提示
     *
     * @param versionUpdateBean
     */
    private void showVersionUpdateDialog(final VersionUpdateBean versionUpdateBean) {
        if (versionUpdateDialog == null) {
            versionUpdateDialog = new VersionUpdateDialog(MainActivity.this);
        }
        versionUpdateDialog.setData(versionUpdateBean, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                versionUpdateDialog.dismissDialog();
                HttpAsyncTask.getInstance().downloadApk(MainActivity.this, versionUpdateBean.getApkUrl());
            }
        });
        if (versionUpdateBean.getCurrentVersion() == 3) {
            versionUpdateDialog.tv_update_cancel.setText("退出应用");
            versionUpdateDialog.tv_update_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    versionUpdateDialog.dismissDialog();
                    finish();
                    System.exit(0);
                }
            });
        }
        versionUpdateDialog.showDialog();
    }







}
